package com.hs.jhzd.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hs.jhzd.entity.Equipment;
import com.hs.jhzd.repository.EquipmentRepository;

@Controller
@RequestMapping("/e")
public class EquipmentController {

  @Autowired
  private EquipmentRepository repository;

  @Value("${jsbh}")
  private String jsbh;

  @RequestMapping("/admin/main")
  public String listPage(Model model, String jsbh) {
    if (StringUtils.isBlank(jsbh) || StringUtils.equals(jsbh, "null")) {
      return "redirect:/content/admin/main?jsbh=" + this.jsbh;
    }
    List<Equipment> equipments = repository.findByJsbhOrderByJsh(jsbh);
    model.addAttribute("jsbh", jsbh);
    model.addAttribute("equipments", equipments);

    Map<String, String> equipmentTypes = new HashMap<>();
    equipmentTypes.put("equipment", "设备");
    equipmentTypes.put("client", "客户端");
    model.addAttribute("equipmentTypes", equipmentTypes);

    return "equipment-list";
  }

  @RequestMapping("/findByJsbh")
  @ResponseBody
  public List<Equipment> findByJsbh(String jsbh) {
    return repository.findByJsbhOrderByJsh(jsbh);
  }

  @RequestMapping("/save")
  @ResponseBody
  public boolean save(Equipment equipment) {

    repository.save(equipment);
    return true;
  }

  @RequestMapping("/findById")
  @ResponseBody
  public Equipment findById(Long id) {
    Optional<Equipment> equipment = repository.findById(id);
    return equipment.isPresent() ? equipment.get() : null;
  }

  @RequestMapping("/findByIp")
  @ResponseBody
  public Equipment findByIp(HttpServletRequest request, @RequestParam(required = true) String jsbh,
      @RequestParam(required = true) String type) {
    return repository.findByJsbhAndIpAndType(jsbh, request.getRemoteAddr(), type);
  }

  @RequestMapping("/del")
  @ResponseBody
  public boolean del(Long id) {
    repository.deleteById(id);
    return true;
  }
}
